//
//  ImageSelectionController.m
//  COIN 4
//
// Copyright 2010 The MITRE Corporation. All rights reserved.
//

#import <MobileCoreServices/UTCoreTypes.h>
#import "ImageSelectionController.h"

@implementation ImageSelectionController

@synthesize delegate;
@synthesize albumButton;
@synthesize cameraButton;
@synthesize imageView;
@synthesize imagePickerController;

-(IBAction)savePressed:(id)sender
{
	if ([delegate respondsToSelector:@selector(didSaveItem)])
	{
		[delegate didSaveItem];
	}
}

- (void)viewDidLoad
{
	if (imagePickerController == nil)
	{
		imagePickerController = [[UIImagePickerController alloc] init];
	}
	imagePickerController.allowsEditing = YES;
	imagePickerController.delegate = self;		
		
	UIBarButtonItem *doneButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(savePressed:)] autorelease];
	self.navigationItem.rightBarButtonItem = doneButton;
	
    [super viewDidLoad];
}

- (IBAction)grabAlbum
{
	imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
	[self presentModalViewController:imagePickerController animated:YES];
}

- (IBAction)grabCamera
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
	{
		imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
	}
	else
	{
		imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	}
    [self presentModalViewController:imagePickerController animated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	[picker dismissModalViewControllerAnimated:YES];

	NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if (CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo)
	{               
        UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
        if (!image)
		{
			image = [info objectForKey:UIImagePickerControllerOriginalImage];             
		}
		[image retain];
		NSLog(@"image size = %f x %f, scale = %f", image.size.width, image.size.height, image.scale);
		imageView.image = image;
	}
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[picker dismissModalViewControllerAnimated:YES];
}

@end
